04 Basics of Building Widgets

Published

June 5, 2025

Modified

June 7, 2025

Read and Study

将某个JavaScript库整合到R中的第一步就是:学习这个JavaScript库。

  1. 阅读库的简介,了解这个库的功能,输入,输出。
  2. 阅读安装文档,了解这个库的依赖。
  3. 以某个例子为切入点,深入了解将库整合到R中的难易程度。
  4. 阅读API文档,准确把握API的使用。
  5. 多使用库,实现对库API的精简与提升。

Candidate Libraries

下面介绍一些htmlwidgets中常见的JavaScript库,并展示这些库在html中使用的共通点:

  1. 引入js库
  2. 声明一个展示图片的div。
  3. js获取图片的div位置,使用绘图结果替代div中的内容。

Plotly.js

plotly.js是plotlyR包的底层依赖库。其官方文档地址为:https://plotly.com/javascript 。下面是一个在html文本中简单使用的例子。

<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">

<head>
  <!-- Import library -->
  <script src="https://cdn.plot.ly/plotly-3.0.1.min.js" charset="utf-8"></script>
</head>

<body>
  <!-- div to hold visualisation -->
  <div id="chart" style="width:600px;height:400px;"></div>
  <!-- Script to create visualisation -->
  <script>
    el = document.getElementById('chart');
    Plotly.newPlot(el, [{
      x: [1, 2, 3, 4, 5],
      y: [1, 2, 4, 8, 16]
    }]
    );
  </script>
</body>

</html>

Highchart.js

highchart.js 是另外一个常见的绘图库,但不是全部免费,其官网为:https://www.highcharts.com 。

<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
  <!-- Import library -->
  <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
  <!-- div to hold visualisation -->
  <div id="chart" style="width:100%;height:400px;"></div>
  <!-- Script to create visualisation -->
  <script>
    var myChart = Highcharts.chart('chart', {
        xAxis: {
            categories: ['Apples', 'Bananas', 'Oranges']
        },
        series: [{
            name: 'Jane',
            data: [1, 0, 4]
        }, {
            name: 'John',
            data: [5, 7, 3]
        }]
    });
  </script>
</body>
</html>

Chart.js

chart.js 以免费和便捷API出名,其官网为:https://www.chartjs.org 。

<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
  <!-- Import library -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <!-- canvas to hold visualisation -->
  <canvas id="chart"></canvas>
  <!-- Script to create visualisation -->
  <script>
    var el = document.getElementById('chart').getContext('2d');
    var myChart = new Chart(el, {
      type: 'bar',
      data: {
        labels: [
          'Red', 'Blue', 'Yellow', 'Green',
          'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3]
        }]
      }
    });
  </script>
</body>
</html>

How it works

  1. 创建一个html文件。
  2. 在html文件中引入Chart.js库。
  3. 创建一个html元素(例如div),用于绘制图表。
  4. R将绘图数据转换为能被绘图模块使用的JSON格式,并嵌入到html文件中。
  5. 上述所有元素能在Rmarkdown,Shiny或其他环境中运行。

flowchart LR
    subgraph i1[R environment]
        A[Data]
        B[Chart options]
    end
    subgraph i2[HTML]
        C[JSON]
        D[Dependencies]
        E[JavaScript]
        F[HTML element]
    end
    A -->C
    B -->C
    C -->E
    D -->E
    E -->F
    style i1 fill:#FFF
    style i2 fill:#FFF

Back to top